package pers.kw.server.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.kw.exceptions.BizException;
import pers.kw.server.persist.dao.StorageDao;
import pers.kw.server.persist.dao.StorageRecordDao;
import pers.kw.server.persist.entity.StorageDO;
import pers.kw.server.persist.entity.StorageRecordDO;
import pers.kw.storage.dto.UpdateStorageReqDto;
import pers.kw.utils.DoWrapUtil;

import javax.annotation.Resource;

/**
 * 库存服务
 */
@Slf4j
@Service
public class StorageService {

    @Resource
    private StorageDao storageDao;

    @Resource
    private StorageRecordDao storageRecordDao;

    @Transactional(rollbackFor = Exception.class)
    public void updateStorage(UpdateStorageReqDto reqDto) {
        log.info("更新库存start...入参：{}", JSON.toJSONString(reqDto));
        StorageDO storageDO = storageDao.findByGoodsNo(reqDto.getGoodsNo());
        if (storageDO == null) {
            throw new BizException("商品库存信息不存在");
        }
        //更新库存
        if (storageDO.getGoodsNum() < reqDto.getGoodsNum()) {
            throw new BizException("库存不足");
        }
        Long afterNum = storageDO.getGoodsNum() - reqDto.getGoodsNum();
        Long beforeNum = storageDO.getGoodsNum();
        storageDO.setGoodsNum(afterNum);
        DoWrapUtil.update(storageDO, false);
        storageDao.save(storageDO);
        //保存库存变更记录
        StorageRecordDO storageRecordDO = new StorageRecordDO();
        DoWrapUtil.insert(storageRecordDO, false, false);
        storageRecordDO.setGoodsNo(storageDO.getGoodsNo());
        storageRecordDO.setBeforeNum(beforeNum);
        storageRecordDO.setAfterNum(afterNum);
        storageRecordDO.setMemo(reqDto.getMemo());
        storageRecordDao.save(storageRecordDO);
        log.info("更新库存end...");
    }
}
